package com.cardone.common.function;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import lombok.Setter;

import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import com.cardone.common.util.MapperUtils;
import com.cardone.context.ContextHolder;
import com.cardone.context.Contexts;
import com.cardone.context.DictionaryException;

/**
 * 代理简单函数
 *
 * @author yaohaitao
 *
 */
public class ProxySimpleFunction implements ProxyFunction {
	/**
	 * 方法名称
	 */
	@Setter
	private String methodName;

	/**
	 * bean对象
	 */
	@Setter
	private Object service;

	@Override
	public Object execution(final String loginUserId, final String parameters) {
		if (this.service == null) {
			throw new DictionaryException("service 未配置");
		}

		if (StringUtils.isBlank(this.methodName)) {
			throw new DictionaryException("methodName 未配置");
		}

		ContextHolder.setId(loginUserId);

		ContextHolder.setStringValue(Contexts.parameters.name(), parameters);

		try {
			final Method[] methods = this.service.getClass().getMethods();

			Method srcMethod = null;

			for (final Method method : methods) {
				if (StringUtils.equals(this.methodName, method.getName()) && (method.getParameterTypes().length < 2)) {
					srcMethod = method;

					break;
				}
			}

			if (srcMethod == null) {
				throw new DictionaryException("methodName 不包含");
			}

			Object[] args = null;

			if (!ArrayUtils.isEmpty(srcMethod.getParameterTypes())) {
				args = new Object[srcMethod.getParameterTypes().length];

				if (String.class.equals(srcMethod.getParameterTypes()[0])) {
					args[0] = parameters;
				} else {
					args[0] = MapperUtils.getBeanForJson(srcMethod.getParameterTypes()[0], parameters);
				}
			}

			return MethodUtils.invokeMethod(this.service, this.methodName, args);
		} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
			throw new DictionaryException(e.getMessage(), e);
		}
	}
}